package cn.xl.xxl.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore.Images.Media;
import android.util.Base64;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.xl.xxl.imagecache.MemoryCache;

public class PictureUtil {

	private MemoryCache memoryCache = new MemoryCache();
	private Map<ImageView, String> imageViews = Collections
			.synchronizedMap(new WeakHashMap<ImageView, String>());

	private static ExecutorService executorService;

	public PictureUtil() {
		executorService = Executors.newFixedThreadPool(5);
	}

	/**
	 * 
	 * @param filePath
	 * @return
	 */
	public static String bitmapToString(String filePath) {

		Bitmap bm = getSmallBitmap(filePath);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
		byte[] b = baos.toByteArray();

		return Base64.encodeToString(b, Base64.DEFAULT);

	}

	public static byte[] bitmapTobyte(String filePath) {

		Bitmap bm = getSmallBitmap(filePath);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
		byte[] b = baos.toByteArray();

		return b;

	}



	/**
	 * 
	 * @param options
	 * @param reqWidth
	 * @param reqHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			// Calculate ratios of height and width to requested height and
			// width
			final int heightRatio = Math.round((float) height
					/ (float) reqHeight);
			final int widthRatio = Math.round((float) width / (float) reqWidth);

			// Choose the smallest ratio as inSampleSize value, this will
			// guarantee
			// a final image with both dimensions larger than or equal to the
			// requested height and width.
			inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
		}

		return inSampleSize;
	}

	/**
	 *
	 * @return
	 */
	public static Bitmap getSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 480, 800);
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 * @return
	 */
	public void DisplayMinSmallBitmap(String imgPath, ImageView imageView,
			boolean HDimg) {
		imageViews.put(imageView, imgPath);

		Bitmap bitmap = memoryCache.get(imgPath);
		if (bitmap != null) {
			imageView.setImageBitmap(bitmap);
		} else {

			queuePhoto(imgPath, imageView, HDimg);
		}
	}

	private void queuePhoto(String url, ImageView imageView, boolean HDimg) {
		PhotoToLoad p = new PhotoToLoad(url, imageView);
		executorService.submit(new PhotosLoader(p, HDimg));
	}

	// Task for the queue
	private class PhotoToLoad {
		public String url;
		public ImageView imageView;

		public PhotoToLoad(String u, ImageView i) {
			url = u;
			imageView = i;
		}
	}

	class PhotosLoader implements Runnable {
		PhotoToLoad photoToLoad;
		boolean HDimg = false;

		PhotosLoader(PhotoToLoad photoToLoad, boolean HDimg) {
			this.photoToLoad = photoToLoad;
			this.HDimg = HDimg;
		}

		@Override
		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			Bitmap bmp = null;
			if (HDimg) {
				bmp = getSmallBitmap(photoToLoad.url);
			} else {
				bmp = getMinSmallBitmap(photoToLoad.url);
			}
			memoryCache.put(photoToLoad.url, bmp);
			if (imageViewReused(photoToLoad))
				return;
			BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);

			Activity a = (Activity) photoToLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	/**
	 * 
	 * @param photoToLoad
	 * @return
	 */
	boolean imageViewReused(PhotoToLoad photoToLoad) {
		String tag = imageViews.get(photoToLoad.imageView);
		if (tag == null || !tag.equals(photoToLoad.url))
			return true;
		return false;
	}

	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		PhotoToLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, PhotoToLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (imageViewReused(photoToLoad))
				return;
			if (bitmap != null) {
				photoToLoad.imageView.setImageBitmap(bitmap);
			}
		}
	}

	public void clearMemoryCache() {
		memoryCache.clear();
	}

	/**
	 *
	 * @return
	 */
	public static Bitmap getMinSmallBitmap(String filePath) {
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(filePath, options);
		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, 48, 80);
		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(filePath, options);
	}

	/**
	 *
	 * @param path
	 */
	public static void deleteTempFile(Context context, String path) {
		File file = new File(path);
		if (file.exists()) {
			file.delete();
			context.getContentResolver().delete(Media.EXTERNAL_CONTENT_URI,
					Media.DATA + "=?", new String[] { path });
		}
	}

	/**
	 */
	public static void galleryAddPic(Context context, String path) {
		Intent mediaScanIntent = new Intent(
				Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		File f = new File(path);
		Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		context.sendBroadcast(mediaScanIntent);
	}

	/**
	 *
	 * @return
	 */
	public static File getAlbumDir() {
		// File dir = new File(
		// Environment
		// .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
		// getAlbumName());
		File dir = new File(FileManager.getSaveFilePath());
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return dir;
	}

	/**
	 *
	 * @return
	 */
	public static String getAlbumName() {
		return "Scheduling";
	}

	/**
	 *
	 * */

	public static String saveAsImage(String photoPatch, String photoName) {

		if (photoPatch != null) {
			try {

				File file = new File(photoPatch);
				String path = file.getAbsolutePath();
				int end = path.lastIndexOf("/");
				String newPaht = path.substring(0, end);
				photoPatch = newPaht + "/" + photoName + ".jpg";
				file.renameTo(new File(photoPatch));
				// Bitmap bm = BitmapFactory.decodeFile(photoPatch);
				// Bitmap bm = PictureUtil.getSmallBitmap(photoPatch);
				// File file = new File(PictureUtil.getAlbumDir(), "picc_" +
				// photoName+".jpg");
				// FileOutputStream fos = new FileOutputStream(file);
				// bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
				// photoPatch = file.getAbsolutePath();

			} catch (Exception e) {
			}
		}
		return photoPatch;
	}

	public static String savePhotoToSDCard(Bitmap photoBitmap, String path) {
		if (path != null) {
			File photoFile = new File(path);
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
							fileOutputStream)) {
						fileOutputStream.flush();
					}
				}
			} catch (Exception e) {
			} finally {
				try {
					fileOutputStream.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return path;
	}

	public static boolean isImage(String imagePath) {
		try {
			File f = new File(imagePath);
			if (!f.exists()) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}
}
